import axios from "axios";
import router from "../../route";
import CXMessageUtils from "./CXMessageUtils";
import Config from "../../config"

const {baseUrl} = Config

const instance = axios.create({
  baseURL: baseUrl,
  timeout: 3000,
  headers: {
    "Content-Type": "application/json",
    "connect-src": "",
  }
});

instance.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (data.code === 0) {
      return Promise.resolve(data.data as any);
    } else if (data.code === 1) {
      if (data.errcode === 1001) {
        CXMessageUtils.CX_Error("登录过期，请重新登录")
        router.push({name: "login"});
        return Promise.reject("登录过期，请重新登录");
      }
      CXMessageUtils.CX_Error(data.message)
      return Promise.reject(data.message);
    } else if (data.code === 2) {
      router.push({name: "login"});
      CXMessageUtils.CX_Error(data.message)
      return Promise.reject(data.message);
    } else {
      CXMessageUtils.CX_Error(data.message)
      router.push({name: "login"});
      localStorage.clear();
      return Promise.reject(data.message || "未知错误");
    }
  },
  (error) => {
    if (error.message === "Request failed with status code 404") {
      const errorMessage = "接口被吃掉啦~~~";
      CXMessageUtils.CX_Error(errorMessage);
      return Promise.reject(errorMessage);
    } else {
      const errorMessage = error.response?.data?.message || "请求出错" + error;
      console.log("错误信息：", error);
      CXMessageUtils.CX_Error(errorMessage);
      return Promise.reject(errorMessage);
    }
  }
);

export const RequestUtils = ({url, method, data, timeout}: {
  url: string,
  method: string,
  data?: any,
  timeout?: number
}) => {
  const token = localStorage.getItem("token")
  return instance({
    method: method || "get",
    url: `/${url}`,
    data: data,
    timeout: timeout || 5000,
    headers:{
      "token": token,
    }
  });
};
